<?php
/**
 * Created by PhpStorm.
 * User: cowthan
 * Date: 2018/7/14
 * Time: 下午4:47
 *
 * 安全数组，简化空，默认值，不存在的键的问题
 */

class SafeAssoc
{


    public static function create(){
        return new SafeAssoc();
    }

    private $arr;

    private function __construct()
    {
        $this->arr = [];
    }


    public function put($key, $value){
        $this->arr[$key] = $value;
        return $this;
    }

    public function putArray(array $array){
        foreach ($array as $k => $v){
            $this->put($k, $v);
        }
    }

    public function get($key, $defaultValue){
        if(isset($this->arr[$key])){
            $value = $this->arr[$key];
            if($value == null) return $defaultValue;
            return $value;
        }
        return $defaultValue;
    }

    public function checkFormat($key, $func, $errorCode, $error){

        if(!$func($this->arr[$key])){
            throw new \CommonException($error, $errorCode);

        }
        return true;
    }

//    public function test(){
//
//
//
//    }

}